<?php

/**
 * CodeRS - Atviras kodas Lietuvai
 * Copyright (C) 2007 CodeRS www.coders.lt info@coders.lt
 * MightMedia TVS
 * Sesijos - darbas su sesijomis.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 * 
 * Ši programa yra laisva. Jūs galite ją platinti ir/arba modifikuoti
 * remdamiesi Free Software Foundation paskelbtomis GNU Bendrosios
 * Viešosios licencijos sąlygomis: 2 licencijos versija, arba (savo
 * nuožiūra) bet kuria vėlesne versija.
 * 
 * Ši programa platinama su viltimi, kad ji bus naudinga, bet BE JOKIOS
 * GARANTIJOS; be jokios numanomos PERKAMUMO ar TINKAMUMO KONKRETIEMS
 * TIKSLAMS garantijos. Žiūrėkite GNU Bendrąją Viešąją licenciją norėdami
 * sužinoti smulkmenas.
 * 
 * Jūs turėjote kartu su šia programa gauti ir GNU Bendrosios Viešosios
 * licencijos kopija; jei ne - rašykite Free Software Foundation, Inc., 59
 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**/

/*
Dar galima prideti
if (isset($_SERVER['HTTP_REFERER'])) $ref = $_SERVER['HTTP_REFERER'];
else $ref = 'Direct Link';
*/
class session {
	public $user_data = array();
	private $session_id = "";
	private $session_data = "";
	const cookiepath = "/";
	const cookiedomain = DOMAIN;
	const cookiesecure = 0;//Saugus sausainelis: Galima ijungti tik jeigu jusu HTTP serveris dirba su SSL
	
	public function prisijungti() {
		global $db, $_POST, $loginERROR;
		$result = $db->uzklausa("SELECT * FROM ".T_USERS." WHERE `username`='".$db->fix($_POST['vartotojas'])."' AND `pass`='".md5($_POST['slaptazodis'])."'",__FILE__,__LINE__);
		if ($db->rows($result) != 0) {
			$data = $db->masyvas($result);
			if ($data['active'] != 0) {
				$atsiminti = isset($_POST['atsiminti']) ? true : false;
				$db->uzklausa("DELETE  ".T_SESSIONS." WHERE `id`='".$this->session_id."'");
				$this->sukurti($data['user_id'], $atsiminti);
				$db->uzklausa("UPDATE  ".T_USERS." SET `lastlogin`='".time()."' WHERE `user_id`='".$data['user_id']."'");
			}
		} else {
			$db->uzklausa("INSERT INTO `".LENTELES_PRIESAGA."logai` SET `action`='Klaida prisijungiant: User: ".$db->fix($_POST['vartotojas'])." Pass: ".$db->fix($_POST['slaptazodis'])."', `time`='".time() ."', `ip`='".IP."'",__FILE__,__LINE__);
			$loginERROR = "Neteisingi duomenys!";
		}
		$db->free_result($result);
		return "";
	}
	public function atsijungti() {
		global $db, $_COOKIE;
		
		$this->session_data = isset($_COOKIE["mm_dat"]) ? $_COOKIE["mm_dat"] : "";
		$this->session_id = isset($_COOKIE["mm_sid"]) ? $_COOKIE["mm_sid"] : "";
	
		// Patikrinam ar $session_id nera kenksmingo kodo
		if (!preg_match("/^[A-Za-z0-9]*$/", $this->session_data)) $this->session_data = "";
		if (!preg_match("/^[A-Za-z0-9]*$/", $this->session_id)) $this->session_id = "";

		$db->uzklausa("UPDATE ".T_USERS." SET `lastvisit`=`".time()."` WHERE `user_id`!='1'");

		$db->uzklausa("DELETE FROM ".T_SESSIONS." WHERE `id`='".$this->session_id."'");
		setcookie("mm_sid", '', time()-3600*24*30, self::cookiepath, self::cookiedomain, self::cookiesecure);
		
		if ($this->session_data != "") {
			$db->uzklausa("DELETE FROM ".T_SESSIONS_KEYS." WHERE `key_id`='".$this->session_data."'");
			setcookie("mm_dat", '', time()-3600*24*30, self::cookiepath, self::cookiedomain, self::cookiesecure);
		}
		
		define("PRISIJUNGES", false);
		header("Location: ?");//prisijungti.phpPAGR_URL
	}

	public function sukurti($user_id = "", $atsiminti = false) {
		global $db;
		
		// Sugeneruojame session_id
		do {
			$this->session_id = md5(microtime());
			$rez = $db->uzklausa("SELECT * FROM ".T_SESSIONS." WHERE `id`='".$this->session_id."'");
			if ($db->rows($rez) == 0) $kartot = 0;
			else $kartot = 1;
		} while($kartot == 1);
		
		
		// Vartotojui
		if ($user_id != "") {
			$db->uzklausa("INSERT INTO ".T_SESSIONS." SET `id`='".$this->session_id."', `user_id`='".(int) $user_id."', `pradzia`='".time()."', `dabar`='".time()."', `galioja`='".(time() + 300)."', `ip`='".IP."', `narsykle`='".$db->fix(NARSYKLE)."', `psl`='".$db->fix(PSL)."', `spaud`='1'");
			
			setcookie("mm_sid", $this->session_id, 0, self::cookiepath, self::cookiedomain, self::cookiesecure);//Galioja tol kol narsykle uzdaroma
			
			if ($atsiminti == true) {
				$db->uzklausa("INSERT INTO ".T_SESSIONS_KEYS." SET `key_id`='".$this->session_id."', `user_id`='".$user_id."', `ip`='".IP."', `narsykle`='".$db->fix(NARSYKLE)."'");
				
				setcookie("mm_dat", $this->session_id, time() + 3600*24*30, self::cookiepath, self::cookiedomain, self::cookiesecure);
			}
			define("PRISIJUNGES", false);
			header("Location: ?");//prisijungti.phpPAGR_URL

			return $this->user_data;
		} else {
			// Svečiui
			$db->uzklausa("INSERT INTO ".T_SESSIONS." SET `id`='".$this->session_id."', `user_id`='1', `pradzia`='".time()."', `dabar`=".time().", `galioja`='".(time() + 300)."', `ip`='".IP."', `narsykle`='".$db->fix(NARSYKLE)."', `psl`='".$db->fix(PSL)."', `spaud`=1");
			setcookie("mm_sid", $this->session_id, 0, self::cookiepath, self::cookiedomain, self::cookiesecure);//Galioja tol kol narsykle uzdaroma
			
			define("PRISIJUNGES", false);
			return "";
		}
	}

	public function tikrinti() {
		global $db, $_COOKIE;
		
		$this->user_data = "";
		
		$this->session_data = isset($_COOKIE["mm_dat"]) ? $_COOKIE["mm_dat"] : "";
		$this->session_id = isset($_COOKIE["mm_sid"]) ? $_COOKIE["mm_sid"] : "";
		
		// Patikrinam ar nera kenksmingo kodo
		if (!preg_match("/^[A-Za-z0-9]*$/", $this->session_data)) $this->session_data = "";
		if (!preg_match("/^[A-Za-z0-9]*$/", $this->session_id)) $this->session_id = "";
		//$session_data = md5($session_data);
		//$session_id = md5($session_id);
		
		// Jeigu automatinis prisijungimas yra (jeigu nera buvimo sesijos ji sukuriama)
		if ($this->session_data != "") {
			//Egzistuoja
			if ($this->session_id != "")
				$rez = $db->uzklausa("SELECT s.*, sk.*, u.* FROM ".T_SESSIONS." s, ".T_SESSIONS_KEYS." sk, ".T_USERS." u WHERE sk.key_id='".$this->session_data."' AND s.id='".$this->session_id."' AND u.user_id=sk.user_id AND sk.user_id=s.user_id AND sk.ip='".IP."' AND sk.narsykle='".$db->fix(NARSYKLE)."'");
			else
				$rez = $db->uzklausa("SELECT u.*, s.* FROM ".T_SESSIONS_KEYS." s, ".T_USERS." u WHERE s.key_id='".$this->session_data."' AND u.user_id=s.user_id AND s.ip='".IP."' AND s.narsykle='".$db->fix(NARSYKLE)."'");
			//Jeigu nera tokio sausainio...
			if($db->rows($rez) != 0) {
				$this->user_data = $db->masyvas($rez);
				
				//Jeigu nera buvimo sesijos ji sukuriama
				if ($this->session_id == "") {
					do {
						$this->session_id = md5(microtime());
						$rez = $db->uzklausa("SELECT * FROM ".T_SESSIONS." WHERE `id`='".$this->session_id."'");
						if ($db->rows($rez) == 0) {
							$kartoti = false;
						} else {
							$kartoti = true;
						}
					} while($kartoti == true);
			
					$db->uzklausa("INSERT INTO ".T_SESSIONS." SET `id`='".$this->session_id."', `user_id`='".$this->user_data['user_id']."', `pradzia`='".time()."', `dabar`='".time()."' `galioja`='".(time() + 300)."', `ip`='".IP."', `narsykle`='".$db->fix(NARSYKLE)."', `psl`='".$db->fix(PSL)."', `spaud`=1");
					setcookie("mm_sid", $this->session_id, 0, self::cookiepath, self::cookiedomain, self::cookiesecure);
				} else {
					// Atnaujinam
					$db->uzklausa("UPDATE ".T_SESSIONS." SET `dabar`='".time()."', `galioja`='".(time() + 300)."', `psl`='".$db->fix(PSL)."', `spaud`=`spaud`+1");
				}
				define("PRISIJUNGES", true);
				return TRUE;
				
			} else {
				// Gali buti bandymas atspeti sausaini - galima registruoti bandymus ir ban IP
				return false;
			}
		} elseif ($this->session_id != "") {
			//Jeigu yra tik sesijos_ID tada tikrinam ar svecias ar vartotojas
			$rez = $db->uzklausa("SELECT u.*, s.* FROM ".T_SESSIONS." s, ".T_USERS." u WHERE s.id='".$this->session_id."' AND s.user_id=u.user_id AND s.ip='".IP."' AND s.narsykle='".$db->fix(NARSYKLE)."'");
			
			if($db->rows($rez) != 0) {
				$this->user_data = $db->masyvas($rez);
				// yra session_id
				$db->uzklausa("UPDATE ".T_SESSIONS.", ".T_USERS." u SET u.lastvisit = '".time()."', `dabar`='".time()."', `galioja`='".(time() + 300)."', `psl`='".$db->fix(PSL)."', `spaud`=`spaud`+1 WHERE `id`='".$this->session_id."' AND `ip`='".IP."'");
				if ($this->user_data['user_id'] != 1) {
				// Tai vartotojas
					define("PRISIJUNGES", true);
					return TRUE;
				} else {
					// yra session_id, bet tai svecias
					$db->uzklausa("UPDATE ".T_SESSIONS." SET `dabar`='".time()."', `galioja`='".(time() + 300)."', `psl`='".$db->fix(PSL)."', `spaud`=`spaud`+1 WHERE `id`='".$this->session_id."' AND `ip`='".IP."'");
					define("PRISIJUNGES", false);
					return "";//false buvo
				}
			} else {
				$this->sukurti();
				// Tikriausiai bando atspeti sesija tad reiktu deti log ir po to gal net ir ban, aisku gali būti, kad sesija baigesi.
				return "";//false buvo
			}
			//$db->free_result($rez);
		} else {
			// Jeigu is vis nieko nera
			$this->sukurti();
			return "";
		}
	}

	public function session_isvalyti() {
		global $db;
		global $config;

		#### Kiek testavau - Duombaze neatsinaujina ####
		$db->uzklausa("UPDATE ".T_USERS." u, ".T_SESSIONS." s SET u.lastvisit=s.dabar WHERE s.galioja<'".(time() - (3600 * 5))."' AND u.user_id=s.user_id AND s.user_id!='0'");

		// LT Sesijos galiojimo laikas [ sekundėmis ] (3600)
		$db->uzklausa("DELETE FROM ".T_SESSIONS." WHERE galioja<'".(time() - (3600 * 5))."'");
		
		/*
		if ($config['max_autologin_time']) {
			$db->uzklausa('DELETE FROM '.T_SESSIONS_KEYS.'	WHERE last_logins<'.(time() - (86400 * (int) $config['max_autologin_time'])));
		}
		*/
	}
}
?>
